﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ZX.DAL.DBExtend;
using System.Collections;
using ZX.BLL.ClientMobi.Message;
using System.Data;
using System.Text.RegularExpressions;

namespace ZX.WebApp.EHR
{
    public partial class MsgReplyPage : System.Web.UI.Page
    {
        private IDictionary<string, object> PageRefParams = new Dictionary<string, object>();

        private RoleReplyDefault ReplyGroup = new RoleReplyDefault();

        public DataTable V_MsgReply = null;

        //显示状态标记位
        public bool IsEditBlock = false;
        public bool IsReplyBlock = false;
        public bool PState = false;


        protected void Page_Load(object sender, EventArgs e)
        {
            PageRefParams.Add("ID", Request.QueryString["ID"]);
            PageRefParams.Add("UserID", Request.QueryString["UserID"]);

            #region Modify:查看、修改页面状态 
            PageRefParams.Add("ps", Request.QueryString["ps"]);
            PState = (PageRefParams.ContainsKey("ps") && PageRefParams["ps"]!= null) ? true : false;
            #endregion

            if (!IsPostBack)
            {
                

                ReplyGroup.Title = "回复规则 ";
                GetData();
            }
            

        }

        //外观
        private object GetObjForUserParams(IDictionary<string, object> paramsList)
        {
            DbSql dbsql = new DbSql();
            object result = "";
            if (paramsList.ContainsKey("Table"))
            {
                string MessageID = (paramsList.ContainsKey("MessageID")) ? paramsList["MessageID"].ToString() : "";
                //if (string.IsNullOrEmpty(MessageID)) return "";
                switch (paramsList["Table"].ToString())
                {
                    case "V_MsgReply":
                        {
                            System.Data.DataTable dt = dbsql.ExecuteQuery(" select * From V_MsgReply where ID='" + PageRefParams["ID"].ToString() + "'");
                            if (dt != null && dt.Rows.Count > 0)
                            {
                                result = dt;
                            }
                            else
                                result = null;
                        } break;
                    case "DatSysNewsMonth_Depart":
                        {
                            result = "";
                            System.Data.DataTable dd = dbsql.ExecuteQuery(@" select x.*, y.DeptName From DatSysNewsMonth_Depart as x inner join
                    DatDepartment as y on x.DeptID= y.DeptID
                    where x.MessageID='" + MessageID + "'  order by y.Sort desc");
                            if (dd != null && dd.Rows.Count > 0)
                            {
                                foreach (DataRow item in dd.Rows)
                                {
                                    result += ((result == "") ? "" : ",") + item["DeptName"].ToString();
                                }

                            }


                        } break;
                    case "DatSysNewsMonth_logo":
                        {
                            if (paramsList.ContainsKey("ID"))
                            {
                                result = "";
                                System.Data.DataTable ddlog = dbsql.ExecuteQuery(" select * From DatSysNewsMonth_log where ID='" + paramsList["ID"].ToString() + "'");
                                if (ddlog != null && ddlog.Rows.Count > 0)
                                {
                                    result = ddlog.Rows[0]["BeforeVal"].ToString();
                                }
                            }
                            else
                            {
                                System.Data.DataTable ddlog = dbsql.ExecuteQuery(" select * From DatSysNewsMonth_log where MessageID='" + MessageID + "' order by OptTime desc");
                                if (ddlog != null && ddlog.Rows.Count > 0)
                                {
                                    result = ddlog;
                                }
                                else
                                    result = null;
                            }
                            


                        } break;

                    case "DatDepartment":
                        {
                            result = new DataTable();
                            System.Data.DataTable dd = dbsql.ExecuteQuery(@" select DeptID, DeptName From [DatDepartment] as x where deptType=3  and (x.ExpireDate >= GETDATE() or x.ExpireDate = '1900-01-01' or x.ExpireDate is null) order by DeptName asc");
                            if (dd != null && dd.Rows.Count > 0)
                            {
                                result = dd;

                            }


                        } break;
                }

            }

            return result;
        }

        private void GetData()
        {
            IDictionary<string, object> paramsList = new Dictionary<string, object>();
            if (PageRefParams.ContainsKey("ID"))
            {
                paramsList.Add("Table", "V_MsgReply");
                paramsList.Add("MessageID", PageRefParams["ID"].ToString());
                System.Data.DataTable dt = GetObjForUserParams(paramsList) as DataTable;
                if (dt != null)
                {
                    //
                    #region display Department
                    paramsList.Clear();
                    paramsList.Add("Table", "DatSysNewsMonth_Depart");
                    paramsList.Add("MessageID", dt.Rows[0]["ID"].ToString());
                    ltDepartment.Text = GetObjForUserParams(paramsList) as string;
                    #endregion

                    #region display New Contents
                    var cc = dt.Rows[0]["content"].ToString();

                    paramsList.Clear();
                    paramsList.Add("Table", "DatSysNewsMonth_logo");
                    paramsList.Add("MessageID", dt.Rows[0]["ID"].ToString());
                    DataTable nlogTable = GetObjForUserParams(paramsList) as DataTable;
                    if (nlogTable != null)
                    {
                        cc = nlogTable.Rows[0]["AfterVal"].ToString();

                        this.DropDownList1.Items.Clear();
                        this.DropDownList1.Items.Add(new ListItem("请选择历史版本", ""));
                        this.DropDownList1.DataSource = nlogTable;
                        this.DropDownList1.DataTextField = "OptTime";
                        this.DropDownList1.DataValueField = "ID";
                        this.DropDownList1.DataBind();
                    }


                    cc = Regex.Replace(cc, "(\r\n){2}", "\r\n");
                    this.ltContent.Text = Regex.Replace(cc, "\r\n", "<br/>");
                    this.tbEditContent.Text = cc;

                    dt.Rows[0]["content"] = cc;
                    #endregion

                    #region show depament's data 
                    paramsList.Clear();
                    paramsList.Add("Table", "DatDepartment");
                    paramsList.Add("MessageID", dt.Rows[0]["ID"].ToString());
                    DataTable depaTab = GetObjForUserParams(paramsList) as DataTable;
                    if (depaTab != null && depaTab.Rows.Count > 0)
                    {
                        DepamentList.DataSource = depaTab;
                        DepamentList.DataBind();
                    }


                    #endregion


                    this.ltCreatePeopleName.Text = dt.Rows[0]["createPeopleName"].ToString();
                    this.ltTitle.Text = dt.Rows[0]["title"].ToString();
                    //this.ltContent.Text = dt.Rows[0]["content"].ToString().Replace(Environment.NewLine, "<div></div>");

                }
            }
            BinderToTab();
        }

        private object GetDataItemsCheckedValue(bool isResetCheckedState)
        {
            string[] resultArr = null;
            string result = string.Empty;
            for (int i = 0; i < this.DepamentList.Items.Count; i++)
            {
                CheckBox cb = this.DepamentList.Items[i].FindControl("cbRule") as CheckBox;
                if (cb != null && cb.Checked)
                {
                    if (isResetCheckedState)
                        cb.Checked = false;
                    else
                        result += ((result == string.Empty) ? "" : ",") + (this.DepamentList.Items[i].FindControl("hide2") as Literal).Text;
                }
            }

            resultArr = (result != string.Empty) ? result.Split(',') : null;
            return result;

        }


        private void Sava()
        {
            int IsLDHF = 0;

            if (string.IsNullOrEmpty(this.tbContent.Text))
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "script",
                    "CallBackError('回复内容不能为空!');", true);
                return;
            }

            if (this.cbIsLDHF.Checked)
            {
                IsLDHF = 1;
            }

            //部门
            string bmItems = GetDataItemsCheckedValue(false) as string;

            IDictionary<string, object> saveParams = new Dictionary<string, object>();
            saveParams.Add("ID", PageRefParams["ID"].ToString());
            saveParams.Add("UserID", PageRefParams["UserID"].ToString());
            saveParams.Add("Content", this.tbContent.Text.Trim());
            saveParams.Add("ReplyTime", DateTime.Now);
            saveParams.Add("IsRead", 0);
            saveParams.Add("ChangeType", IsLDHF);
            saveParams.Add("DeptDescription", bmItems);

            IMessagePly mp = ReplyGroup.Instance() as IMessagePly;
            if (mp != null)
            {
                mp.Save(saveParams);

                this.tbContent.Text = "";

                GetDataItemsCheckedValue(true);
                BinderToTab();
            }
        }

        private void BinderToTab()
        {
            DataTable datab = new DataTable();
            IDictionary<string, object> sqlParams = new Dictionary<string, object>();
            IMessagePly mp = ReplyGroup.Instance() as IMessagePly;

            sqlParams.Add("sql", " select * From MsgReply where 1=1 and MsgID='" + PageRefParams["ID"].ToString() + "'  order by ReplyTime Desc");

            datab = mp.GetListByTSQL(sqlParams) as DataTable;
            if (datab != null)
            {
                if (datab.Rows.Count > 0) 
                    IsReplyBlock = true;
                else
                    IsReplyBlock = false;
                //throw new Exception(datab.Rows.ToString());
                this.Repeater1.DataSource = datab;
                this.Repeater1.DataBind();
                this.Repeater2.DataSource = datab;
                this.Repeater2.DataBind();
            }

        }

        #region 事件
        //回复
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            Sava();
        }

        //编辑 
        protected void Button2_Click(object sender, EventArgs e)
        {
            IDictionary<string, object> sqlParams = new Dictionary<string, object>();
            IMessagePly mp = ReplyGroup.Instance() as IMessagePly;

            //new value:
            string AfterInputVal = this.tbEditContent.Text.Trim();



            IDictionary<string, object> paramsList = new Dictionary<string, object>();
            paramsList.Add("Table", "V_MsgReply");
            paramsList.Add("MessageID", PageRefParams["ID"].ToString());
            System.Data.DataTable dt = GetObjForUserParams(paramsList) as DataTable;

            if (dt != null && dt.Rows.Count > 0)
            {
                if (AfterInputVal.Length == dt.Rows[0]["content"].ToString().Length)
                {
                    this.IsEditBlock = false;
                    return;
                }
                sqlParams.Add("sql", @" insert into [DatSysNewsMonth_log] ([ID]  ,[MessageID]  ,[BeforeVal]  ,[AfterVal]  ,[ChangeType]  ,[OptTime]) 
values (newid(), '" + dt.Rows[0]["ID"].ToString() + "', '" + dt.Rows[0]["content"].ToString() + "', '" + AfterInputVal + "', 0, GetDate() ) Update [DatSysNewsMonth] set [content]='" + AfterInputVal + "' where ID='" + dt.Rows[0]["ID"].ToString() + "'");
                sqlParams.Add("acrtion", "ExecuteScalar");
                mp.GetListByTSQL(sqlParams);

                GetData();
                this.IsEditBlock = false;
            }
        }

        protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
        {
            IDictionary<string, object> paramsLists = new Dictionary<string, object>();
            paramsLists.Add("Table", "V_MsgReply");
            paramsLists.Add("MessageID", PageRefParams["ID"].ToString());
            System.Data.DataTable dt = GetObjForUserParams(paramsLists) as DataTable;

            //((DataTable)MsgReplyPage.V_MsgReply).Rows[0]["content"]
            if ((sender as DropDownList) != null && string.IsNullOrEmpty((sender as DropDownList).SelectedValue))
            {
                string result1 = dt.Rows[0]["content"].ToString();
                result1 = Regex.Replace(result1, "(\r\n){2}", "\r\n");
                this.ltContent.Text = Regex.Replace(result1, "\r\n", "<br/>");
                this.IsEditBlock = false;
                return;
            }

            IDictionary<string, object> paramsList = new Dictionary<string, object>();
            paramsList.Add("Table", "DatSysNewsMonth_logo");
            paramsList.Add("MessageID", "");
            paramsList.Add("ID", this.DropDownList1.SelectedValue.ToString());

            string result = GetObjForUserParams(paramsList) as string;

            result = Regex.Replace(result, "(\r\n){2}", "\r\n");
            this.ltContent.Text = Regex.Replace(result, "\r\n", "<br/>");
            //this.ltContent.Text = result;
            this.IsEditBlock = false;
        }
        #endregion

        protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "del")
            {
                var delID = e.CommandArgument.ToString();

                DataTable datab = new DataTable();
                IDictionary<string, object> sqlParams = new Dictionary<string, object>();
                IMessagePly mp = ReplyGroup.Instance() as IMessagePly;

                sqlParams.Add("sql", " Delete From MsgReply where ID='" + delID + "'");
                sqlParams.Add("acrtion", "ExecuteScalar");
                mp.GetListByTSQL(sqlParams);
                BinderToTab();
            }
        }

        protected void btnEdit_Click(object sender, EventArgs e)
        {
            IDictionary<string, object> paramsLists = new Dictionary<string, object>();
            paramsLists.Add("Table", "V_MsgReply");
            paramsLists.Add("MessageID", PageRefParams["ID"].ToString());
            System.Data.DataTable dt = GetObjForUserParams(paramsLists) as DataTable;

            var cc = dt.Rows[0]["content"].ToString();
            cc = Regex.Replace(cc, "(\r\n){2}", "\r\n");
            this.tbEditContent.Text = cc;
            this.IsEditBlock = true;
        }

        protected void btnReply_Click(object sender, EventArgs e)
        {
            this.IsReplyBlock = true;
        }

        

    }
}